package com.origin.onlinesys.common.controllers;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.runtime.log.NullLogChute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
/**
 * Created by Administrator on 2015/1/6.
 */
@Controller
public class BaseController {
    static {
            Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new NullLogChute());
    }
    private static final Logger log = Logger.getLogger(BaseController.class);

    protected int pageSize = 10;
    protected SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private ServletContext servletContext;

    @ExceptionHandler(SQLException.class)
    public @ResponseBody JSONObject handlerDbException(SQLException e){
        return null;
    }
    protected String getUploadPath(String project,String suffix){
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
        File file = new File(this.projectPath()).getParentFile().getParentFile();
        file = new File(file,"uploadFile/"+project); if(!file.exists())file.mkdirs();
        return file.getPath()+"/"+dateformat.format(new Date())+"_"+UUID.randomUUID().toString()+suffix;
    }
    /**
     * 用velocity写出静态页面
     * @param templetName 模板名称
     * @param varBingName 绑定数据的名称
     * @param varBingData 绑定数据
     * @param targetName  写出文件名称
     */
    protected void writerHtml(String  templetName,String varBingName,
                              Object varBingData,String targetName){
        //设置加载路径
        String  parentPath = this.templetNavPath();
        Properties prop = new Properties();
//        prop.put("file.resource.loader.class",
//                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        prop.put("file.resource.loader.path", parentPath);
        prop.put("input.encoding", "utf-8");
        prop.put("output.encoding", "utf-8");
        log.info("------velocity.resource.path--==================v.2.0.0----"+prop.toString());
        Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new NullLogChute());
        Velocity.init(prop);
        //初始化上下文
        VelocityContext context=new VelocityContext();
        //添加数据到上下文中
        context.put(varBingName, varBingData);
        Template template= Velocity.getTemplate(templetName);
        //生成html页面
        PrintWriter pw= null;
        try {
            pw = new PrintWriter(parentPath+targetName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        template.merge(context, pw);
        //关闭流
        pw.close();
    }
    /**
     * 删除模板
     */
    protected void delNavRole(){
        File file = new File(this.templetNavPath());
        File[] files = file.listFiles();
        for(File file1: files){
            if(file1.getAbsolutePath().indexOf("navRole")>=0) try {
                FileUtils.forceDelete(file1);} catch (IOException e) {e.printStackTrace();}
        }
    }
    protected String templetNavPath(){
        StringBuilder sb = new StringBuilder(this.projectPath());
        return  sb.append(File.separator).append("WEB-INF").append(File.separator)
                .append("views").append(File.separator).append("pages").append(File.separator).toString();
    }

    protected String projectPath(){
        return servletContext.getRealPath("/");
    }
}
